package com.fmsz.physicalheadline.fragments.head;


import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.fmsz.physicalheadline.BR;
import com.fmsz.physicalheadline.R;
import com.fmsz.physicalheadline.adapter.top.TopRecycleAdapter;
import com.fmsz.physicalheadline.application.MyApplication;
import com.fmsz.physicalheadline.databinding.FragmentDynamicBinding;
import com.fmsz.physicalheadline.entity.top.DynamicData;
import com.fmsz.physicalheadline.entity.top.DynamicEntity;
import com.fmsz.physicalheadline.interfaces.HttpService;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class DynamicFragment extends Fragment implements Callback<DynamicEntity> {


    private FragmentDynamicBinding bind;
    private TopRecycleAdapter<Object> adapter;

    public DynamicFragment() {

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = DataBindingUtil.inflate(inflater, R.layout.fragment_dynamic, container, false).getRoot();
        bind = DataBindingUtil.bind(view);
        initView();
        initData();
        return view;
    }

    private void initData() {
        Calendar calendar = Calendar.getInstance();
        HttpService httpService = ((MyApplication) getActivity().getApplication()).getHttpService();
        httpService.getTopDynamicData(String.valueOf(calendar.getTimeInMillis())).enqueue(this);
    }

    private void initView() {
        Map<Class<?>,Pair<Integer,Integer>> map = new HashMap<>();
        map.put(null,Pair.create(R.layout.dynamic_item, BR.dynamic));
        adapter = new TopRecycleAdapter<>(getContext(),new ArrayList<>(),map);
        bind.recycleViewDynamic.setAdapter(adapter);
    }

    @Override
    public void onResponse(Call<DynamicEntity> call, Response<DynamicEntity> response) {
        if (response.body()!=null) {
            if (response.body().getCode()!=200) {
                return;
            }
            DynamicData data = response.body().getData();
            adapter.addAll(data.getSnapshots());
        }
    }

    @Override
    public void onFailure(Call<DynamicEntity> call, Throwable t) {
        t.printStackTrace();
        Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
    }
}
